<?php
session_start();
include '../conn.php'; // 确保这是正确的路径到你的数据库连接文件
// 检查是否设置了所有必要的参数
if (!isset($_REQUEST['uid']) || !isset($_REQUEST['gid'])) {
    echo "非法访问！";
    exit;
}
$uid = $_REQUEST['uid'];
// print_r($uid);
$gid = $_REQUEST['gid'];
// print_r($gid);
$content = $_GET['content'];
$content = urldecode($content);
// print_r($content);
// 检查用户是否存在
$sql = "SELECT * FROM user WHERE id = " . $uid;
$result = $conn->query($sql);
// 用户存在才能进行评论
if ($result && $result->num_rows > 0) {
    // 获取查询结果的第一行
    $row = $result->fetch_assoc();	
	// 打印结果
	// print_r($row['uname']);
	// print_r($content);
	// 实现用户只能评论一次
	// 获取当前登录的id和当前的商品id去数据库里面查看是否能查到这个数据，能查到的话就是已经评论了，不给评论了
	// 检查当前用户是否已经给当前看的商品进行了评论
	$checkSql = "SELECT * FROM comment WHERE user_id = ? AND good_id = ?";
	$checkStmt = $conn->prepare($checkSql);
	$checkStmt->bind_param("ii", $uid, $gid);
	$checkStmt->execute();
	$checkResult = $checkStmt->get_result();
	 if ($checkResult->num_rows > 0) {
		 echo "<script>alert('已经评论了！请勿重复评论'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";
		 echo "已经评论了！";
	 } else{
		$sql2 = "INSERT INTO comment (good_id, user_id, content,creator) VALUES (?, ?, ?,?)";
		$stmt2 = $conn->prepare($sql2);
		// 解决中文评论问题（优化）
		$stmt2->bind_param("iiss", $gid, $uid, $content,$row['uname']);
		if ($stmt2->execute()) {
			echo "<script>alert('评论成功！'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";
			echo "评论成功！";
			$conn->close();
		  }else {
			echo "评论失败";
			$conn->close();
		  }
	 }
} else {
	echo "没有找到用户或查询失败";
}


?>